package cn.al2.util.demo;

import cn.al2.util.GenerateUtil;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MappedByteBufferDemo {


    public static void main(String[] args) throws Exception {
        // 创建一个足够大的文件
        String filePath = "example.txt";
        if (!Files.exists(Paths.get(filePath))) {
            Files.createFile(Paths.get(filePath));
        }

        // 打开一个RandomAccessFile对象来获取文件通道
        RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();

        // 将文件通道的一部分映射到内存中
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, GenerateUtil.getInstance().staticProduct().size()*1000);

        // 写入数据到内存映射区
//        for (int i = 0; i < 256; i++) {
//            mappedByteBuffer.put((byte) 'A');
//        }


        long start = System.currentTimeMillis();
        for (String logStr : GenerateUtil.getInstance().staticProduct()) {
            // 将字符串转换为字节数组
            byte[] bytes = logStr.getBytes();

            // 写入字节数组到文件
//            mappedByteBuffer.put(bytes);

            mappedByteBuffer.put(bytes);
        }

        // 确保所有映射的字节都被写入到磁盘上的文件中
        mappedByteBuffer.force();


        long end = System.currentTimeMillis();

        System.out.println("MappedByteBufferDemo 文件写入成功 耗时：" + (end - start));

        // 关闭流和文件通道
        fileChannel.close();
        randomAccessFile.close();


    }

}
